<template>
  <h2>进项发票管理</h2>
  <div class="invoice-management">
    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-item">
          <label>单位名称</label>
          <input 
            v-model="searchForm.unitName" 
            type="text" 
            placeholder="请输入单位名称"
            class="form-input"
          />
        </div>
        
        <div class="form-item">
          <label>发票类型</label>
          <select v-model="searchForm.invoiceType" class="form-select">
            <option value="">全部</option>
            <option value='0'>普通发票</option>
            <option value='1'>增值税专用发票</option>
          </select>
        </div>
        
        <div class="form-item">
          <label>发票日期</label>
          <input 
            v-model="searchForm.invoiceDate" 
            type="date" 
            placeholder="请选择发票日期"
            class="form-input"
          />
        </div>
        
        <div class="form-actions">
          <button @click="handleSearch" class="btn btn-primary">
            <i class="icon-search"></i>
            查询
          </button>
          <button @click="handleReset" class="btn btn-secondary">
            <i class="icon-refresh"></i>
            重置
          </button>
        </div>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <button @click="handleAdd" class="btn btn-primary">
        新增
      </button>
      <button @click="handleDelete" class="btn btn-primary">
        删除
      </button>
     
      <button @click="handleExport" class="btn btn-primary">
        导出
      </button>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <table class="data-table">
        <thead>
          <tr>
            <th>
              <input 
                type="checkbox" 
                v-model="selectAll"
                @change="handleSelectAll"
                class="checkbox"
              />
            </th>
            <th>发票号</th>
            <th>开票单位</th>
            <th>发票类型</th>
            <th>发票金额</th>
            <th>税率</th>
            <th>税额</th>
            <th>发票日期</th>
            <th>备注</th>
            <th>制单人</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="12" class="loading-cell">
              <div class="loading-spinner">加载中...</div>
            </td>
          </tr>
          <tr v-else-if="tableData.length === 0">
            <td colspan="12" class="empty-cell">
              暂无数据
            </td>
          </tr>
          <tr v-else v-for="(item, index) in tableData" :key="item.id">
            <td>
              <input 
                type="checkbox" 
                v-model="item.selected"
                @change="handleSelectItem"
                class="checkbox"
              />
            </td>
            <td>{{ item.invoiceNo }}</td>
            <td>{{ item.distributorName }}</td>
            <td>
              <span :class="getInvoiceTypeClass(item.invoiceType)">
                {{ item.invoiceType === 'False' ? '普通发票' : '增值税专用发票' }}
              </span>
            </td>
            <td>{{ formatAmount(item.invoiceAmount) }}</td>
            <td>{{ (item.taxRate * 100).toFixed(1) }}%</td>
            <td>{{ formatAmount(item.taxAmount) }}</td>
            <td>{{ formatDate(item.invoiceDate) }}</td>
            <td>{{ item.notes || '-' }}</td>
            <td>{{ item.preparer }}</td>
            <td>{{ formatDate(item.createdTime) }}</td>
            <td>
              <div class="action-buttons">
                <button @click="handleEdit(item)" class="btn-action btn-edit">编辑</button>
                <button @click="handleDeleteItem(item)" class="btn-action btn-delete">删除</button>
                <button @click="handleView(item)" class="btn-action btn-view">查看</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <div class="pagination-info">
        <span>共{{ totalPages }}页/{{ totalRecords }}条数据</span>
        <div class="page-size-selector">
          <span>每页显示</span>
          <select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select">
            <option value="2">2</option>
            <option value="20">20</option>
            <option value="50">50</option>
            <option value="100">100</option>
          </select>
          <span>条</span>
        </div>
      </div>
      <div class="pagination-controls">
        <button 
          @click="goToPage(currentPage - 1)" 
          :disabled="currentPage === 1"
          class="btn-pagination"
        >
          &lt;
        </button>
        
        <button 
          v-for="page in visiblePages" 
          :key="page"
          @click="goToPage(page)"
          :class="['btn-pagination', { active: page === currentPage }]"
        >
          {{ page }}
        </button>
        
        <button 
          v-if="showEllipsis"
          class="btn-pagination disabled"
        >
          ...
        </button>
        
        <button 
          v-if="showLastPage"
          @click="goToPage(totalPages)"
          :class="['btn-pagination', { active: currentPage === totalPages }]"
        >
          {{ totalPages }}
        </button>
        
        <button 
          @click="goToPage(currentPage + 1)" 
          :disabled="currentPage === totalPages"
          class="btn-pagination"
        >
          &gt;
        </button>
      </div>
      
      <div class="pagination-jump">
        <span>跳至</span>
        <input 
          v-model="jumpToPage" 
          type="number" 
          min="1" 
          :max="totalPages"
          @keyup.enter="handleJumpToPage"
          class="jump-input"
        />
        <span>页</span>
      </div>
    </div>

    <!-- 底部说明 -->
    <div class="footer-description">
      <p><strong>进项发票：</strong>是指你购买货物或者劳务,付钱后,别人给你开的发票。你是发票上的购买方。</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { setApi, GATEWAY_URL } from '@/api'

// 路由实例
const router = useRouter()

// 消息提示方法
const showSuccess = (message: string) => {
  const toast = document.createElement('div')
  toast.className = 'toast toast-success'
  toast.textContent = message
  document.body.appendChild(toast)
  
  setTimeout(() => toast.classList.add('show'), 100)
  
  setTimeout(() => {
    toast.classList.remove('show')
    setTimeout(() => document.body.removeChild(toast), 300)
  }, 3000)
}

const showError = (message: string) => {
  const toast = document.createElement('div')
  toast.className = 'toast toast-error'
  toast.textContent = message
  document.body.appendChild(toast)
  
  setTimeout(() => toast.classList.add('show'), 100)
  
  setTimeout(() => {
    toast.classList.remove('show')
    setTimeout(() => document.body.removeChild(toast), 300)
  }, 5000)
}

const showWarning = (message: string) => {
  const toast = document.createElement('div')
  toast.className = 'toast toast-warning'
  toast.textContent = message
  document.body.appendChild(toast)
  
  setTimeout(() => toast.classList.add('show'), 100)
  
  setTimeout(() => {
    toast.classList.remove('show')
    setTimeout(() => document.body.removeChild(toast), 300)
  }, 4000)
}

// 搜索表单数据
const searchForm = reactive({
  unitName: '', // 对应 DistributorName
  invoiceType: '', // 对应 InvoiceType
  invoiceDate: '' // 对应 InvoiceDate
})

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(2)
const totalPages = ref(0)
const totalRecords = ref(0)
const jumpToPage = ref(1)

// 全选状态
const selectAll = ref(false)

// 计算属性
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, start + 4)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

const showEllipsis = computed(() => {
  return totalPages.value > 5 && currentPage.value < totalPages.value - 2
})

const showLastPage = computed(() => {
  return totalPages.value > 5 && currentPage.value < totalPages.value - 2
})

// 获取发票列表数据
const fetchInvoiceList = async () => {
  try {
    loading.value = true
    
    // 构建查询参数对象
    const params: any = {
      PageIndex: currentPage.value,
      PageSize: pageSize.value
    }
    
    // 添加搜索条件（只添加非空值）
    if (searchForm.unitName && searchForm.unitName.trim()) {
      params.DistributorName = searchForm.unitName.trim()
    }
    if (searchForm.invoiceType && searchForm.invoiceType.trim()) {
      params.InvoiceType = searchForm.invoiceType.trim()
    }
    if (searchForm.invoiceDate && searchForm.invoiceDate.trim()) {
      params.InvoiceDate = searchForm.invoiceDate.trim()
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    console.log('请求参数:', params)
    console.log('请求URL:', `${GATEWAY_URL.SET_READ}/api/InboundOutboundInvoice/GetInboundInvoices`)
    
    const response = await setApi.getInboundInvoices(params)
    
    console.log('API 响应:', response)
    console.log('响应状态:', response.status)
    console.log('响应数据:', response.data)
    
    if (response.data.code === 200) {
      const responseData = response.data.data
      tableData.value = responseData.data.map((item: any) => ({
        ...item,
        selected: false
      }))
      totalRecords.value = responseData.totalCount
      totalPages.value = responseData.totalPage
      
      // 更新跳转页码输入框的值
      jumpToPage.value = currentPage.value
      
      console.log(`成功获取 ${responseData.data.length} 条数据，共 ${responseData.totalCount} 条，${responseData.totalPage} 页`)
    } else {
      showError(`获取数据失败: ${response.data.message}`)
    }
  } catch (error: any) {
    console.error('获取数据出错:', error)
    console.error('错误详情:', error.message)
    showError('获取数据出错，请重试')
  } finally {
    loading.value = false
  }
}

// 方法
const handleSearch = () => {
  currentPage.value = 1
  fetchInvoiceList()
}

const handleReset = () => {
  searchForm.unitName = ''
  searchForm.invoiceType = ''
  searchForm.invoiceDate = ''
  currentPage.value = 1
  fetchInvoiceList()
}

const handleAdd = () => {
  // 跳转到新增发票页面
  router.push('/AddInvoiceManagement')
}

const handleDelete = async () => {
  const selectedItems = tableData.value.filter(item => item.selected)
  if (selectedItems.length === 0) {
    showWarning('请选择要删除的项目')
    return
  }
  
  if (confirm(`确定要删除选中的 ${selectedItems.length} 条记录吗？`)) {
    try {
      const ids = selectedItems.map(item => item.id)
      const response = await setApi.deleteListInboundOutboundInvoice(ids)
      
      if (response.code === 200) {
        showSuccess('删除成功')
        fetchInvoiceList()
      } else {
        showError(`删除失败: ${response.message}`)
      }
    } catch (error: any) {
      console.error('删除出错:', error)
      showError('删除出错，请重试')
    }
  }
}

const handlePrint = () => {
  // 这里实现打印逻辑
}

const handleExport = async () => {
  try {
    // 显示导出提示
    const exportConfirm = confirm('确定要导出所有发票数据到Excel文件吗？')
    if (!exportConfirm) return
    
    // 调用导出接口 
    const response = await setApi.exportInboundInvoicesToExcel()
    
    // 创建下载链接
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '进销发票数据.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    showSuccess('导出成功！')
  } catch (error: any) {
    console.error('导出失败:', error)
    showError('导出失败，请重试')
  }
}

const handleEdit = (item: any) => {
  // 跳转到编辑页面
  router.push(`/UpdateInvoiceManagement/${item.id}`)
}

const handleDeleteItem = async (item: any) => {
  if (confirm(`确定要删除发票 ${item.invoiceNo} 吗？`)) {
    try {
      const response = await setApi.deleteInboundOutboundInvoice(item.id)
      
      if (response.code === 200) {
        showSuccess('删除成功')
        fetchInvoiceList()
      } else {
        showError(`删除失败: ${response.message}`)
      }
    } catch (error: any) {
      console.error('删除出错:', error)
      showError('删除出错，请重试')
    }
  }
}

const handleView = (item: any) => {
  // 跳转到查看页面（只读模式）
  router.push(`/UpdateInvoiceManagement/${item.id}?mode=view`)
}

const handleSelectAll = () => {
  tableData.value.forEach(item => {
    item.selected = selectAll.value
  })
}

const handleSelectItem = () => {
  const selectedCount = tableData.value.filter(item => item.selected).length
  selectAll.value = selectedCount === tableData.value.length
}

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    jumpToPage.value = page
    fetchInvoiceList()
  }
}

const handleJumpToPage = () => {
  goToPage(jumpToPage.value)
}

const handlePageSizeChange = () => {
  currentPage.value = 1
  fetchInvoiceList()
}

const getInvoiceTypeClass = (type: string) => {
  return type === 'False' ? 'invoice-type-ordinary' : 'invoice-type-vat'
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 格式化金额
const formatAmount = (amount: number) => {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

onMounted(() => {
  fetchInvoiceList()
})
</script>

<style scoped>
.invoice-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 搜索区域样式 */
.search-section {
  background: white;
  padding: 20px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  gap: 20px;
  align-items: end;
  flex-wrap: wrap;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 200px;
}

.form-item label {
  font-weight: bold;
  color: #333;
  font-size: 14px;
}

.form-input, .form-select {
  padding: 10px 12px;
  border: 1px solid #ddd;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-input:focus, .form-select:focus {
  outline: none;
  border-color: #007bff;
}

.form-actions {
  display: flex;
  gap: 10px;
}

/* 按钮样式 */
.btn {
  padding: 10px 20px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 5px;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover {
  background: #0056b3;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #545b62;
}

/* 操作按钮区域 */
.action-section {
  background: white;
  padding: 15px 20px;
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
}

/* 表格样式 */
.table-section {
  background: white;
  overflow: hidden;
  margin-bottom: 20px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.data-table th {
  background: #f8f9fa;
  font-weight: bold;
  color: #333;
  position: sticky;
  top: 0;
}

.data-table tbody tr:hover {
  background: #f8f9fa;
}

.checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.invoice-type-ordinary {
  color: #28a745;
  font-weight: bold;
}

.invoice-type-vat {
  color: #dc3545;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-action {
  padding: 4px 8px;
  border: none;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
}

.btn-edit {
  background: #17a2b8;
  color: white;
}

.btn-edit:hover {
  background: #138496;
}

.btn-delete {
  background: #dc3545;
  color: white;
}

.btn-delete:hover {
  background: #c82333;
}

.btn-view {
  background: #6c757d;
  color: white;
}

.btn-view:hover {
  background: #545b62;
}

/* 分页样式 */
.pagination-section {
  background: white;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-info {
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.page-size-select {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  gap: 5px;
  align-items: center;
}

.btn-pagination {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-pagination:hover:not(.disabled) {
  background: #f8f9fa;
}

.btn-pagination.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.btn-pagination:disabled,
.btn-pagination.disabled {
  background: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
}

.pagination-jump {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.jump-input {
  width: 60px;
  padding: 6px 8px;
  border: 1px solid #ddd;
  text-align: center;
}

/* 底部说明 */
.footer-description {
  background: white;
  padding: 20px;
}

.footer-description p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

/* 图标样式 */
.icon-search::before {
  content: "🔍";
}

.icon-refresh::before {
  content: "🔄";
}

/* 加载状态样式 */
.loading-cell, .empty-cell {
  text-align: center;
  padding: 40px;
  color: #666;
  font-size: 16px;
}

.loading-spinner {
  display: inline-block;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .form-item {
    min-width: auto;
  }
  
  .action-section {
    flex-wrap: wrap;
  }
  
  .pagination-section {
    flex-direction: column;
    gap: 15px;
  }
}

@media (max-width: 768px) {
  .invoice-management {
    padding: 10px;
  }
  
  .data-table {
    font-size: 12px;
  }
  
  .data-table th,
  .data-table td {
    padding: 8px 4px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}

/* Toast 消息提示样式 */
.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 12px 20px;
  border-radius: 6px;
  color: white;
  font-weight: 500;
  font-size: 14px;
  z-index: 9999;
  transform: translateX(100%);
  transition: transform 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-width: 300px;
  word-wrap: break-word;
}

.toast.show {
  transform: translateX(0);
}

.toast-success {
  background: #52c41a;
}

.toast-error {
  background: #ff4d4f;
}

.toast-warning {
  background: #faad14;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toast {
    right: 10px;
    left: 10px;
    max-width: none;
    transform: translateY(-100%);
  }
  
  .toast.show {
    transform: translateY(0);
  }
}
</style>
